﻿
crucible.Comment = function(data) {
    var self = this;
    data = data || {};

    this.Id = data.Id;
    this.Node_Id = data.Node_Id;
    this.Body = ko.observable(data.Body);
    this.BodyEdit = ko.observable(data.Body);
    this.Author = data.Author;
    this.Score = ko.observable(data.Score);
    this.Date = data.DateAdded;
    this.IsDeleted = data.IsDeleted;
    this.FormattedBody = ko.computed(function () {
        if (self.IsDeleted) {
            return "[Deleted]";
        }
        return crucible.Comment.bodyConverter.convert(self);
    });
    this.Replies = ko.observableArray();

    this.newReply = ko.observable();
    this.ReplyBoxVisible = ko.observable(false);
    this.ReplyBoxFocused = ko.observable(false);


    this.IsEditing = ko.observable(false);
    this.EditHasFocus = ko.observable(false);
    this.IsDeleting = ko.observable(false);

    

};


crucible.Comment.prototype.startReplying = function() {
    if (!(crucible.userId > 0)) {
        crucible.raiseError("You must be logged in to comment.", true);
        return;
    }

    this.ReplyBoxVisible(true);
    this.ReplyBoxFocused(true);

};

crucible.Comment.prototype.startEditing = function() {
    this.IsEditing(true);
    this.EditHasFocus(true);
};

crucible.Comment.prototype.saveEdit = function () {
    var self = this;
    datacontext.putComment(this, function () {
        self.IsEditing(false);
        self.Body(self.BodyEdit());
    });
};

crucible.Comment.prototype.cancelEdit = function () {
    this.IsEditing(false);
    this.BodyEdit(this.Body());
};

crucible.Comment.prototype.startDeleting = function () {
    this.IsDeleting(true);
};



crucible.Comment.bodyConverter = function() {  // this is a static method on the Comment class
    var converter = Markdown.getSanitizingConverter(),
        convert = function(node) {
            self.node = node;
            return converter.makeHtml(node.Body() || "");
        };

    converter.setAllowLinks(true);

    return {
        convert: convert
    };
}();
